<template>
  <div>
    <sticky :class-name="'sub-navbar'">
      <span style="display: inline-block;margin-right: 50px;font-weight: bold ">防止达到微信API接口访问上限，请先保存草稿，再发布到微信</span>
      <el-button v-loading="loading" type="warning" @click="saveDraftData">草稿</el-button>
      <el-button v-loading="loading" style="margin-left: 10px;" type="success" @click="uploadNews">发布
      </el-button>
    </sticky>
    <el-container style="padding: 20px 0px 30px 30px;">
      <el-aside style="background-color: #f6f8f9;padding: 10px 30px 30px" width="360px">
        <div style="display: block;width:280px;margin: auto;">
          <div v-for="(item, index) in newsList.slice(0,1)" :key="index" :class="item.isBorder ? 'news-main' : 'news-main-noborder'" @click="handlerClickItem(index)">
            <div :class="item.isBorder ? 'news-content' : 'news-content-noborder'">
              <!--<img src="https://picsum.photos/240/140" v-show="!!item.imageUrl"/>-->
              <img v-show="!!item.imageUrl" :src="item.imageUrl" width="240px" height="140px">
              <div class="news-content-title">{{ !!item.title ? item.title : '标题' }}</div>
            </div>
          </div>

          <div v-for="(item, index) in newsList.slice(1)" :key="index + 1" :class="item.isBorder ? 'news-main-item' : 'news-main-item-noborder'" @click="handlerClickItem(index+1)" @mouseover="showDeleteDiv(index+1)" @mouseout="hideDeleteDiv(index+1)">
            <div :class="item.isBorder ? 'news-content-item' : 'news-content-item-noborder'">
              <div class="news-content-item-title">{{ !!item.title ? item.title : '标题' }}</div>
              <div class="news-content-item-img">
                <img v-show="!!item.imageUrl" :src="item.imageUrl" width="100%" height="100%">
              </div>
              <div v-show="item.isShowDeleteDiv" class="news-content-item-delete" @click.stop="handlerDeleteItem(index+1)">
                <i class="el-icon-delete" style="font-size: 30px" @click="" />
              </div>
            </div>
            <div class="hr-div" />
          </div>

          <div v-show="newsList.length < 8" class="news-bottom" @click="handlerAddItem">
            <i class="el-icon-plus news-bottom-plus" />
          </div>

        </div>

      </el-aside>
      <el-main>

        <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="80px">
          <el-form-item :label="tempDesc.title" prop="title">
            <el-input v-model="temp.title" :placeholder="'请输入' + tempDesc.title" style="width: 500px" minlength="1" maxlength="10" />
          </el-form-item>
          <el-form-item :label="tempDesc.digest" prop="digest">
            <el-input v-model="temp.digest" :placeholder="'请输入' + tempDesc.digest" style="width: 500px" minlength="1" maxlength="30" />
          </el-form-item>
          <el-form-item :label="tempDesc.author" prop="author">
            <el-input v-model="temp.author" :placeholder="'请输入' + tempDesc.author" style="width: 500px" minlength="1" maxlength="15" />
          </el-form-item>
          <el-form-item label="封面" style="width: 875px" prop="imageUrl">
            <Upload v-model="temp.imageUrl" />
          </el-form-item>
          <el-form-item label="留言">
            <el-switch v-model="temp.needOpenCommentBoolean" style="margin-right: 20px" />
            <el-radio-group v-model="temp.onlyFansCanComment">
              <el-radio label="0">所有人可留言</el-radio>
              <el-radio label="1">仅粉丝可留言</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="内容" style="width: 85%">
            <Tinymce ref="editor" v-model="temp.content" :height="400" />
          </el-form-item>
        </el-form>

      </el-main>
    </el-container>
  </div>
</template>

<script>
import { addNews, getNews, deleteOneArticle, uploadNews } from '@/api/wx-news-template'
import { getQueryObject } from '@/utils'
import waves from '@/directive/waves'
import Tinymce from '@/components/Tinymce'
import Upload from '@/components/Upload/singleImage'
import Sticky from '@/components/Sticky' // 粘性header组件

import { getShowImageURL } from '@/utils'

// 常量title
const tempDesc = {
  title: '标题',
  author: '作者',
  digest: '摘要',
  imageUrl: '封面',
  content: '内容',
  picPath: ''
}

const tempConst = {
  id: '',
  title: '',
  author: '',
  digest: '',
  imageUrl: '',
  content: '',
  picPath: '',
  needOpenCommentBoolean: true,
  needOpenComment: '1',
  onlyFansCanComment: '0',
  isBorder: false,
  isShowDeleteDiv: false
}

export default {
  components: {
    //      ElAside,
    //      ElContainer
    Tinymce,
    Upload,
    Sticky
  },
  directives: { waves },
  filters: {},
  data() {
    return {
      loading: false,
      tempDesc,
      newsId: '',
      newsList: [], // 总的图文
      temp: Object.assign({}, tempConst),
      rules: {
        title: [{ required: true, message: '请输入' + tempDesc.title, trigger: 'blur' }],
        digest: [{ required: true, message: '请输入' + tempDesc.digest, trigger: 'blur' }],
        author: [{ required: true, message: '请输入' + tempDesc.author, trigger: 'blur' }]
      },
      getNewsData: [],
      deleteArticleIds: []// 保存数据的时候，该ids需要删除
    }
  },
  watch: {
    temp: {
      handler(newValue, oldValue) {
        const _this = this
        var currentIndex = _this.getCurrentIndex()
        _this.newsList[currentIndex].title = _this.temp.title
        _this.newsList[currentIndex].author = _this.temp.author
        _this.newsList[currentIndex].digest = _this.temp.digest
        _this.newsList[currentIndex].imageUrl = _this.temp.imageUrl
        var picPath = getQueryObject(_this.temp.imageUrl).filepath
        _this.newsList[currentIndex].picPath = picPath

        _this.newsList[currentIndex].needOpenCommentBoolean = _this.temp.needOpenCommentBoolean
        _this.newsList[currentIndex].needOpenComment = _this.temp.needOpenCommentBoolean ? '1' : '0'
        _this.newsList[currentIndex].onlyFansCanComment = _this.temp.onlyFansCanComment

        _this.newsList[currentIndex].content = _this.temp.content

        _this.$nextTick(function() {
          // _this.$refs.editor.setContent(_this.temp.content);
        })
      },
      deep: true
    }

  },
  created() {
    this.newsId = this.$route.params.id
    this.getNews()
  },
  methods: {
    saveDraftData() {
      const _this = this

      // validate
      for (var i = 0; i < _this.newsList.length; i++) {
        var _temp = _this.newsList[i]
        if (!_temp.title) {
          this.$message({ message: '请填写第' + (i + 1) + '个图文的' + tempDesc.title, type: 'warning' })
          return false
        }
        if (!_temp.digest) {
          this.$message({ message: '请填写第' + (i + 1) + '个图文的' + tempDesc.digest, type: 'warning' })
          return false
        }
        if (!_temp.author) {
          this.$message({ message: '请填写第' + (i + 1) + '个图文的' + tempDesc.author, type: 'warning' })
          return false
        }
        if (!_temp.imageUrl) {
          this.$message({ message: '请填写第' + (i + 1) + '个图文的' + tempDesc.imageUrl, type: 'warning' })
          return false
        }
        if (!_temp.content) {
          this.$message({ message: '请填写第' + (i + 1) + '个图文的' + tempDesc.content, type: 'warning' })
          return false
        }
      }

      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          var params = { id: this.newsId, list: this.newsList, deleteArticleIds: this.deleteArticleIds }
          addNews(params).then(() => {
            this.$notify({
              title: '成功',
              message: '创建草稿成功',
              type: 'success',
              duration: 2000,
              onClose() {
                _this.$store.dispatch('delView', _this.$route)
                _this.$router.push({ path: '/wxmpMaterialManage/newsTemplateList' })
              }
            })
          })
        }
      })
    },
    uploadNews() {
      const _this = this

      // validate
      for (var i = 0; i < _this.newsList.length; i++) {
        var _temp = _this.newsList[i]
        if (!_temp.title) {
          this.$message({ message: '请填写第' + (i + 1) + '个图文的' + tempDesc.title, type: 'warning' })
          return false
        }
        if (!_temp.digest) {
          this.$message({ message: '请填写第' + (i + 1) + '个图文的' + tempDesc.digest, type: 'warning' })
          return false
        }
        if (!_temp.author) {
          this.$message({ message: '请填写第' + (i + 1) + '个图文的' + tempDesc.author, type: 'warning' })
          return false
        }
        if (!_temp.imageUrl) {
          this.$message({ message: '请填写第' + (i + 1) + '个图文的' + tempDesc.imageUrl, type: 'warning' })
          return false
        }
        if (!_temp.content) {
          this.$message({ message: '请填写第' + (i + 1) + '个图文的' + tempDesc.content, type: 'warning' })
          return false
        }
      }

      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          var params = { id: this.newsId, list: this.newsList, deleteArticleIds: this.deleteArticleIds }
          uploadNews(params).then(() => {
            this.$notify({
              title: '成功',
              message: '发布成功',
              type: 'success',
              duration: 2000,
              onClose() {
                _this.$store.dispatch('delView', _this.$route)
                _this.$router.push({ path: '/wxmpMaterialManage/newsTemplateList' })
              }
            })
          })
        }
      })
    },
    handlerClickItem(index) {
      const _this = this
      _this.resetTemp()
      // 修改border样式，先全部重置，在进行赋值
      for (var i = 0; i < _this.newsList.length; i++) {
        _this.newsList[i].isBorder = false
      }
      _this.newsList[index].isBorder = true
      _this.temp = _this.newsList[index]
    },
    handlerAddItem() {
      const _this = this
      _this.resetTemp()

      const _temp = Object.assign({}, tempConst)
      _temp.isBorder = true
      // 把之前存在的border修改为无border样式
      for (var i = 0; i < _this.newsList.length; i++) {
        _this.newsList[i].isBorder = false
      }
      _this.newsList.push(_temp)
      // console.log(_this.newsList);
    },
    addDefault() {
      const _this = this
      const _temp = Object.assign({}, tempConst)
      _temp.isBorder = true
      _this.newsList.push(_temp)
    },
    showDeleteDiv(index) {
      const _this = this
      const _temp = Object.assign({}, _this.newsList[index])
      _temp.isShowDeleteDiv = true
      _this.$set(_this.newsList, index, _temp)
      // console.log(index + ";" + _this.newsList[index].isShowDeleteDiv);
    },
    hideDeleteDiv(index) {
      const _this = this
      const _temp = Object.assign({}, _this.newsList[index])
      _temp.isShowDeleteDiv = false
      _this.$set(_this.newsList, index, _temp)
      // console.log(index + ";" + _this.newsList[index].isShowDeleteDiv);
    },
    handlerDeleteItem(index) {
      // console.log("handlerDeleteItem" + index);
      const _this = this

      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 先清空数据
        _this.resetTemp()
        // 如果删除的当前item，存在id，需要在后台同时删除
        if (_this.newsList[index].id) {
          _this.deleteArticleIds.push(_this.newsList[index].id)
        }

        // 当前页面删除
        _this.newsList.splice(index, 1)

        // 把之前存在的border修改为无border样式
        for (var i = 0; i < _this.newsList.length; i++) {
          _this.newsList[i].isBorder = false
        }
        // 删除之后，默认选中第一个
        _this.newsList[0].isBorder = true

        const currentIndex = _this.getCurrentIndex()
        _this.temp = _this.newsList[currentIndex]
      })
    },
    getCurrentIndex() {
      const _this = this
      for (var i = 0; i < _this.newsList.length; i++) {
        if (_this.newsList[i].isBorder) {
          return i
        }
      }
    },
    resetTemp() {
      this.temp = Object.assign({}, tempConst)
      // console.log(this.temp);
      this.$nextTick(function() {
        this.$refs.editor.setContent(this.temp.content)
      })
    },
    getNews() {
      const _this = this
      var params = { id: _this.newsId }
      getNews(params).then(res => {
        _this.getNewsData = res.data

        if (_this.getNewsData.length == 0) {
          _this.addDefault()
        } else {
          for (var i = 0; i < res.data.length; i++) {
            const _temp = Object.assign({}, tempConst)
            _temp.id = res.data[i].id
            _temp.title = res.data[i].title
            _temp.author = res.data[i].author
            _temp.digest = res.data[i].digest
            _temp.imageUrl = getShowImageURL(res.data[i].picPath)
            _temp.content = res.data[i].content
            _temp.picPath = res.data[i].picPath
            _temp.needOpenCommentBoolean = res.data[i].needOpenComment == '1'
            _temp.needOpenComment = res.data[i].needOpenComment
            _temp.onlyFansCanComment = res.data[i].onlyFansCanComment
            if (i == 0) {
              _temp.isBorder = true
              _this.temp = Object.assign({}, _temp)
              _this.$nextTick(function() {
                _this.$refs.editor.setContent(_temp.content)
              })
            }
            _this.newsList.push(_temp)
          }
        }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .news-main{
    background-color: #FFFFFF;
    width: 280px;
    border: 3px solid #67C23A;
    padding: 20px;
    margin: auto;
  }
  .news-main-noborder{
    background-color: #FFFFFF;
    width: 280px;
    //border: 3px solid transparent;
    padding: 20px;
    margin: auto;
  }
  .news-content{
    background-color: #acadae;
    width: 240px;
    height: 140px;
    position: relative;
    margin-left: -3px
  }

  .news-content-noborder{
    background-color: #acadae;
    width: 240px;
    height: 140px;
    position: relative;
  }

  .news-content-title{
    display: inline-block;
    font-size: 15px;
    color: #FFFFFF;
    position: absolute;
    left: 10px;
    bottom: 15px;
  }

  .news-main-item{
    background-color: #FFFFFF;
    border: 3px solid #67C23A;
    padding: 10px 20px;
  }

  .news-main-item-noborder{
    background-color: #FFFFFF;
    //border: 3px solid transparent;
    padding: 10px 20px;
  }

  .news-content-item{
    height: 60px;
    position: relative;
    margin-left: -3px
  }

  .news-content-item-noborder{
    height: 60px;
    position: relative;
  }

  .news-content-item-title{
    display: inline-block;
    font-size: 15px;
    line-height: 60px;
    margin-left: 10px;
  }

  .news-content-item-img{
    float: right;
    display: inline-block;
    height: 50px;
    width: 50px;
    background-color: #acadae;
    margin-top: 5px;
    margin-right: 8px;
  }
  .news-content-item-delete{
    display: block;
    background-color:#606266;
    position: absolute;
    width: 100%;
    text-align:center;
    bottom: -1px;
    opacity: 0.3
  }

  .news-bottom{
    height: 100px;
    background-color: #FFFFFF;
    text-align: center;
    margin: auto
  }
  .news-bottom-plus{
    font-size: 50px;
    color: #979797;
    margin-top: 25px
  }

  .hr-div{
    border-bottom: 1px solid #C0C4CC;display: block
  }

</style>
